package com.xsx.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class HelloServLet implements Servlet {

    public HelloServLet() {
        System.out.println("1 构造器方法");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2.init初始化");
        //1.获取servlet程序的别名 servlet-name的值
        System.out.println("HelloServlet程序的别名是：" + servletConfig.getServletName());
//        2.获取初始化参数init-param
        System.out.println("初始化参数username的值是：" + servletConfig.getInitParameter("userName"));
        System.out.println("初始化参数username的值是：" + servletConfig.getInitParameter("id"));
//        3.获取ServletContext对象
        System.out.println(servletConfig.getServletContext());
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * service方法时专门用来处理请求和响应的
     *
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("3. HelloServLet,被访问了11");
        //类型转换 向下转型 ServletRequest调用自己子类方法
        HttpServletRequest httpservletRequest = (HttpServletRequest) servletRequest;
        //获取是get还是post
        String method = httpservletRequest.getMethod();
        System.out.println(method);
        if ("GET".equals(method)) {
            doGet();
        } else if ("POST".equals(method)) {
            doPost();
        }
    }

    /**
     * GET请求的操作
     */
    public void doGet() {
        System.out.println("get请求");
    }

    /**
     * GET请求的操作
     */
    public void doPost() {
        System.out.println("post请求");

    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("4.destroy 销毁方法");
    }
}
